package top.stackstrace.sock;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

public class MsgWorker implements Handler<Buffer> {
  private int len = -1;
  private int readlen = 0;
  private Buffer buf = Buffer.buffer();
  private static int LEN_SIZE = 4;
  private static String hn = "unkown host";
  private NetSocket socket;
  static{
    try {
      hn = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

  public MsgWorker(NetSocket socket){
    this.socket = socket;
  }

  public void clear(){
    len = -1;
    buf = Buffer.buffer();
  }

  @Override
  public void handle(Buffer buffer){
    if(buffer.length() <= 4){
      System.out.println("invalid msg length: "+buffer.length());
    }else{
      readlen = 0;
      while(readlen < buffer.length()){
        if(len <= 0){
          len = buffer.getInt(readlen);
          readlen += LEN_SIZE;
          System.out.println("get msg len: "+len);
        }
        if(buffer.length()-readlen >= len){
          buf.appendBuffer(buffer,readlen,len);
          readlen+=len;
          String msg = buf.getString(0,buf.length(),"UTF-8");
          clear();
          System.out.println("recv msg:"+msg);
          String reply = "Hello: "+msg+" , from: "+hn;
          Buffer writeBuf = Buffer.buffer();
          byte[] bytes = reply.getBytes(StandardCharsets.UTF_8);
          writeBuf.appendInt(bytes.length);
          writeBuf.appendBytes(bytes);
          socket.write(writeBuf).onFailure(e->{e.printStackTrace();}).onSuccess((e)->{
            System.out.println("send reply success: "+reply);
          });
          continue;
        }
        int rlen = buffer.length() - readlen;
        buf.appendBuffer(buffer,readlen,rlen);
        readlen += rlen;
        len -= rlen;
      }
    }
  }
}
